from rest_framework import serializers

from company.serializers import CompanySerializer
from userinfo.models import User, Company


class RegisterSerializer(serializers.Serializer):
    username = serializers.CharField(required=True, max_length=20, min_length=5, write_only=True)
    password = serializers.CharField(required=True, max_length=13, min_length=5, write_only=True)
    re_password = serializers.CharField(required=True, max_length=13, min_length=5, write_only=True)
    email = serializers.EmailField(required=True, write_only=True)

    def validate(self, attrs):
        username = attrs.get('username')
        password = attrs.get('password')
        re_password = attrs.get('re_password')
        email = attrs.get('email')
        if User.objects.filter(username=username).exists():
            raise serializers.ValidationError('Username is taken.')
        elif User.objects.filter(email=email).exists():
            raise serializers.ValidationError('Email is taken.')
        elif password != re_password:
            raise serializers.ValidationError('Passwords do not match.')
        else:
            return attrs


class LoginSerializer(serializers.Serializer):
    username = serializers.CharField(required=True, max_length=20, min_length=5)
    email = serializers.EmailField(required=True)
    password = serializers.CharField(required=True)
    re_password = serializers.CharField(required=True)

    def validate(self, attrs):
        email = attrs.get('email')
        password = attrs.get('password')
        if email and password:
            user = User.objects.filter(email=email).first()
            if not user:
                raise serializers.ValidationError("请输入正确的邮箱！")
            if not user.check_password(password):
                raise serializers.ValidationError("请输入正确的密码！")
            # 判断状态
            # 为了节省执行SQL语句的次数，这里我们把user直接放到attrs中，方便在视图中使用
            attrs['user'] = user
        else:
            raise serializers.ValidationError('请传入邮箱和密码！')
        return attrs


class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('id', 'username', 'email', 'first_name', 'last_name', 'is_staff', 'role', 'company')


class UpdatePositionSerializer(serializers.ModelSerializer):
    company = CompanySerializer()

    class Meta:
        model = User
        fields = ('id', 'username', 'email', 'first_name', 'last_name', 'is_staff', 'role', 'company')

    def update(self, instance, validated_data):
        instance.company = validated_data.get('company')
        instance.save()
        return instance
